#include <iostream>
#include <string>
#include "Log.hpp"
#include "Socket.hpp"
#include <memory>
#include <cstring>
#include <cerrno>
#include <sys/select.h>
#include <ctime>
using namespace std;
const int num = sizeof(fd_set) * 8;


class SelectServer {
public :
    SelectServer(uint16_t port) 
        :_listensocket(new TcpSocket)
        ,_port(port)
        ,_isrunning(false)
    {

    }

    void Init() {
        // 创建一特监听套接字
        _listensocket->BuildListenSocketMethod(_port, default_backlog);
        for (int i = 0; i < num; i++) {
            _rfds_array[i] = nullptr;
        }
        _rfds_array[0] = _listensocket.get();
    }

    void Handler(fd_set* fds) {
        for (int i = 0; i < num; i++) {
            if (_rfds_array[i] == nullptr) {
                continue;
            }
            if (FD_ISSET(_rfds_array[i]->GetSockFd(), fds)) {
                if (_rfds_array[i]->GetSockFd() == _listensocket->GetSockFd()) {
                    lg.LogMessage(Info, "get a new link!");
                    string clientip;
                    uint16_t clientport;
                    Socket* newsocket = _listensocket->AcceptSocket(&clientip, &clientport);
                    if (newsocket) {
                        // 获取一个新链接
                        // 将新链接加入到_rfds_array
                        int pos = 0;
                        while (pos < num) {
                            if (_rfds_array[pos] == nullptr) {
                                _rfds_array[pos] = newsocket;
                                break;
                            }
                            pos++;
                        }
                        if (pos == num) {
                            // 说明当前可以管理的文件描述符已满，已经处理不了了
                            // 直接关闭
                            newsocket->CloseSockFd();
                            delete newsocket;
                        }
                    } else {
                        lg.LogMessage(Error, "link error");
                    }
                } else {
                    // 收发数据
                    string buffer;
                    bool res = _rfds_array[i]->Recv(&buffer, 1024);
                    if (res) {
                        pthread_mutex_lock(&mtx);
                        cout << "client say# " << buffer << endl;
                        pthread_mutex_unlock(&mtx);
                        string rbuffer = "你好啊!\n";
                        _rfds_array[i]->Send(rbuffer); // 这样写是错误的，只是为了演示
                    } else {
                        // 读取失败，不管为什么，直接关闭
                        _rfds_array[i]->CloseSockFd();
                        delete _rfds_array[i];
                        _rfds_array[i] = nullptr;
                    }
                }
            }
        }

    }

    void Stop() {
        _isrunning = false;
    }

    void Loop() {
        _isrunning = true;
        while (_isrunning) {
            fd_set rfds;
            FD_ZERO(&rfds); // 将文件描述集置零
            // 每次都要将rfds重置
            int max_fd = _listensocket->GetSockFd();
            for (int i = 0; i < num; i++) {
                if (_rfds_array[i] == nullptr) {
                    continue;
                }
                FD_SET(_rfds_array[i]->GetSockFd(), &rfds);
                max_fd = max(max_fd, _rfds_array[i]->GetSockFd());
            }
            struct timeval timeout = { 2, 0 };
            int n = select(max_fd + 1, &rfds, nullptr, nullptr, nullptr);
            if (n > 0) {
                lg.LogMessage(Info, "已有文件描述符就绪: 剩余时间%u.%u", timeout.tv_sec, timeout.tv_usec);
                // 处理读就绪
                Handler(&rfds);
            } else if (n == 0) {
                // 超时返回
                lg.LogMessage(Info, "select 超时返回,剩余时间%u.%u", timeout.tv_sec, timeout.tv_usec);
            } else {
                // select出错了
                lg.LogMessage(Fatal, "select error! errno: %d, errorstring: %s", errno, strerror(errno));
                break;  
            }

        }

    }

    ~SelectServer() {

    }

private :
    unique_ptr<Socket> _listensocket;
    uint16_t _port;
    bool _isrunning;
    Socket* _rfds_array[num];
};


